package com.jijuxie.message.controller;

import com.jijuxie.common.core.R;
import com.jijuxie.framework.config.UploadConfig;
import com.jijuxie.message.domain.ChatMessage;
import com.jijuxie.message.service.IChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 聊天图片控制器
 */
@RestController
@RequestMapping("/chat/image")
public class ChatImageController {

    private static final Logger log = LoggerFactory.getLogger(ChatImageController.class);

    @Autowired
    private IChatMessageService chatMessageService;

    @Value("${upload.path:D:/jijuxie/upload/}")
    private String uploadPath;
    
    @Value("${upload.url:/profile/}")
    private String uploadUrl;

    /**
     * 上传聊天图片
     */
    @PostMapping("/upload")
    public R<Map<String, Object>> upload(@RequestParam("file") MultipartFile file,
                                 @RequestParam Long toUserId,
                                 @RequestParam(required = false, defaultValue = "chat") String imageType) throws IOException {
        // 获取当前登录用户ID
        Long fromUserId = StpUtil.getLoginIdAsLong();
        log.info("上传聊天图片: fromUserId={}, toUserId={}, imageType={}, fileName={}", 
                fromUserId, toUserId, imageType, file.getOriginalFilename());
        
        // 生成文件名
        String fileName = UUID.randomUUID().toString()
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        // 保存文件
        String chatDirPath = uploadPath + "chat/";
        File chatDir = new File(chatDirPath);
        if (!chatDir.exists()) {
            chatDir.mkdirs();
        }
        
        File dest = new File(chatDirPath + fileName);
        file.transferTo(dest);
        
        String imageUrl = uploadUrl + "chat/" + fileName;

        // 创建图片消息
        ChatMessage message = new ChatMessage();
        message.setFromUserId(fromUserId);
        message.setToUserId(toUserId);
        message.setMessageType("image"); // 消息类型为图片
        message.setContent(imageUrl); // 使用图片URL作为内容
        message.setImageUrl(imageUrl); // 存储图片URL
        message.setImageType(imageType); // 类型为聊天图片
        message.setSendTime(LocalDateTime.now());
        message.setReadFlag("0"); // 未读状态
        
        // 保存消息
        chatMessageService.sendMessage(message);
        
        // 返回结果，包含消息ID和图片URL
        Map<String, Object> result = new HashMap<>();
        result.put("messageId", message.getMessageId());
        result.put("imageUrl", imageUrl);
        result.put("fromUserId", fromUserId);
        result.put("toUserId", toUserId);
        result.put("sendTime", message.getSendTime());
        
        return R.ok(result);
    }
} 